from PIL import Image, ImageDraw, ImageFont
import os
from datetime import datetime
from PIL.ExifTags import TAGS, GPSTAGS

def get_capture_time(image_path):
    try:
        with Image.open(image_path) as img:
            exif = img._getexif()
            if exif:
                for tag_id, value in exif.items():
                    tag = TAGS.get(tag_id, tag_id)
                    if tag == 'DateTimeOriginal':
                        # 将时间格式转换为更易读的格式
                        dt = datetime.strptime(value, '%Y:%m:%d %H:%M:%S')
                        return dt.strftime('%Y-%m-%d %H:%M:%S')
    except Exception as e:
        print(f"读取EXIF数据时出错 {image_path}: {e}")
    return None

def add_timestamp_to_image(image_path, output_path):
    try:
        # 以不压缩的方式打开图片
        with Image.open(image_path) as img:
            # 获取原始格式和尺寸
            original_format = img.format
            original_size = img.size
            
            # 创建一个新的图片副本，确保尺寸和模式正确
            if original_format in ['JPEG', 'JPG']:
                new_img = Image.new('RGB', original_size, (255, 255, 255))
                new_img.paste(img, (0, 0))
            else:
                new_img = img.copy()
            
            # 创建绘图对象
            draw = ImageDraw.Draw(new_img)
            
            # 使用微软雅黑字体，大小设为72
            try:
                font = ImageFont.truetype("msyh.ttc", 72)  # 微软雅黑字体
            except:
                try:
                    font = ImageFont.truetype("simhei.ttf", 72)  # 尝试使用黑体
                except:
                    print(f"未找到中文字体，将使用默认字体 - {os.path.basename(image_path)}")
                    font = ImageFont.load_default()
            
            # 获取拍摄时间
            timestamp = get_capture_time(image_path)
            if timestamp:
                text = f"拍摄时间: {timestamp}"
                
                # 获取文本尺寸
                bbox = draw.textbbox((0, 0), text, font=font)
                text_width = bbox[2] - bbox[0]
                text_height = bbox[3] - bbox[1]
                
                # 计算文本位置（右下角）
                width, height = original_size
                x = width - text_width - 40  # 右边距离
                y = height - text_height - 40  # 下边距离
                
                # 橙色文字 (RGB: 255, 165, 0)
                draw.text((x, y), text, font=font, fill=(255, 165, 0))
            
            # 保存图片，确保保持原始大小
            if original_format in ['JPEG', 'JPG']:
                # JPEG特殊处理
                new_img.save(
                    output_path,
                    'JPEG',
                    quality=100,
                    subsampling=0,
                    optimize=False,
                    exif=img.info.get('exif', b'')  # 保留EXIF数据
                )
            else:
                # 其他格式保持原样
                new_img.save(
                    output_path,
                    original_format,
                    quality=100,
                    exif=img.info.get('exif', b'')  # 保留EXIF数据
                )
            
            print(f"已处理: {os.path.basename(image_path)}")
            
    except Exception as e:
        print(f"处理图片时出错 {image_path}: {e}")
        import traceback
        print(traceback.format_exc())

def process_current_folder():
    # 获取当前文件夹
    current_folder = os.getcwd()
    # 创建输出文件夹（使用中文名称）
    output_folder = os.path.join(current_folder, "已添加时间戳")
    
    # 确保输出文件夹存在
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)
    
    # 处理所有图片文件
    processed = False
    for filename in os.listdir(current_folder):
        if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp')):
            input_path = os.path.join(current_folder, filename)
            output_path = os.path.join(output_folder, filename)
            add_timestamp_to_image(input_path, output_path)
            processed = True
    
    if processed:
        print(f"\n处理完成！请在 '{output_folder}' 文件夹中查看处理后的图片。")
    else:
        print("\n当前文件夹中没有找到图片文件。")

if __name__ == "__main__":
    process_current_folder()
    print("所有图片处理完成！")
